﻿SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ARITHABORT ON
GO
SET NUMERIC_ROUNDABORT OFF
GO
SET CONCAT_NULL_YIELDS_NULL ON
GO
SET ANSI_PADDING ON
GO
SET ANSI_WARNINGS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Adrian Kaczmarek
-- Create date: 2013-07-18
-- =============================================
-- Modified date: 2013-09-16
-- Description:	Blokada pobierania tych samych zadań podwójnie
-- =============================================
ALTER PROCEDURE [dbo].[bhp_ReservationMailGetToSend] 
AS
BEGIN

	DECLARE
		@ActionIds	Ids

	BEGIN TRAN

	INSERT INTO @ActionIds
		SELECT
			rm.ActionId
		FROM
			bht_ReservationMails rm
			INNER JOIN bht_MailTemplates mt ON rm.TemplateId = mt.TemplateId
			INNER JOIN REZERWACJA r ON rm.ReservationId = r.idx
		WHERE
			r.del = 0
			AND (rm.SendNotEarlier IS NULL OR rm.SendNotEarlier < GETDATE())

	UPDATE
		bht_ReservationMails
	SET
		SendNotEarlier = DATEADD(MINUTE, 120, GETDATE())
	FROM
		bht_ReservationMails rm
		INNER JOIN @ActionIds x ON rm.ActionId = x.Id

	COMMIT
	
	SELECT
		rm.ActionId,
		rm.ReservationId,
		rm.TemplateId,
		mt.Name,
		REPLACE(mt.DefaultMailTitle, '{Number}', r.numer) DefaultMailTitle,
		mt.AdditionalRecipient
	FROM
		@ActionIds x
		INNER JOIN bht_ReservationMails rm ON x.Id = rm.ActionId
		INNER JOIN bht_MailTemplates mt ON rm.TemplateId = mt.TemplateId
		INNER JOIN REZERWACJA r ON rm.ReservationId = r.idx

END
